package com.playball.lottery.frm.buyhall;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.text.Html;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.playball.lottery.R;
import com.playball.lottery.ApplicationData;
import com.playball.lottery.customview.IntelligenceChaseUpdatePlan;
import com.playball.lottery.customview.ShowCustomDialog;
import com.playball.lottery.customview.ShowCustomDialog2;
import com.playball.lottery.customview.ShowTipDialog;
import com.playball.lottery.frm.help.CaiPiaoHelp;
import com.playball.lottery.frm.yhzx.JddRechargeListActivity;
import com.playball.lottery.frm.yhzx.LoginActivity;
import com.playball.lottery.nt.GetRequestParams;
import com.playball.lottery.util.AbstractActivity;
import com.playball.lottery.util.AppUtils;
import com.playball.lottery.util.Constants;
import com.playball.lottery.util.DefConstants;
import com.playball.lottery.util.GetIDAsyncLoader;
import com.playball.lottery.util.IntelligenceChaseUtil;

/**
 * 智能追号
* @ClassName: IntelligenceChaseActivity 
* @Description: TODO(这里用一句话描述这个类的作用) 
* @author 2w 
* @date 2014年7月22日 下午2:24:14 
*
 */
public class IntelligenceChaseActivity extends AbstractActivity implements OnClickListener , DefConstants {
	
	/**返回按钮*/
	private Button btnBack ;
	/**标题*/
	private TextView txtTitle;
	/**帮助*/
	private Button btnHelp ;
	
	/**距离多少期*/
    private TextView txtDistanceIssue;
    /**距 期  截止时间*/
    private TextView txtStopTime;
    
	/**共选择多少期*/
	private TextView txtTotalIssue;
	/**最低盈利率*/
	private TextView txtIntellRate;
	/**修改按钮*/
	private Button btnUpdate ;
	
	/**列表*/
	private ListView intellChaseListView ;
	
	/**共追多少期*/
	private TextView txtChaseTotalIssue;
	/**共多少钱*/
	private TextView txtTatalMoney;
	/**付款*/
	private Button btnIntellPay ;
	
	
	/**适配器*/
	private IntelligenceChaseAdapter iChaseAdapter ;
	
	
	/**时间 handler*/
	Handler handlerTime = new Handler();
	/**剩余时间*/
	private long endTime; 
	/**期次 id*/
	private String issueID;
	/**期次 name*/
	private String issueName;
	
	/**奖金额*/
	private int prizeIntellChase ;
	
	/**投入的倍数*/
	private int inputMutiple = 1 ;
	/**投入注数  默认1 */
	private int castCount = 1 ;
	/**投入期数  默认10 */
	private int castIsuse = 10 ;
	/** 彩种ID*/
	private int lorID  ;
	/**选择类型  2. 累计盈利不低于  1. 全程盈利率*/
	private int model = 1 ;
	/**累计盈利不低于 默认*/
	private int expectIncome = 100;
	/**全程盈利率 默认 */
	private int expectIncomeRate = 30 ;
	/**0 继续追号  1停止 追号*/
	private int intWinStopChase = 1;
	
	/**数据集合*/
	private List<Map<String, Object>> dataList ;
	/**数据集合新*/
	private List<Map<String, Object>> dataListNew ;
	/**工具类*/
	private  IntelligenceChaseUtil chaseUtil ;
	
	/**判断是不是 加减 还是 其他 过去    1 是加 2 是减 3 输入框的输入 其他不是不是*/
	private int isFormAddOrSub = 0 ;
 
	/**加减  累计投入*/
	private int tmepTotalCost = 0;
	
	/**输入框  得到上一个 */
	private int previousTotalCost = 0;
	
	/**临时倍数*/
	private int tempCastCount = 1 ;
	
	private int buy_icon;
	//数组
	private String[] dyn;
	
	//购买的金额
	private 	int  buyMoney ;
	
	
	private  ShowCustomDialog2.Builder alertbBuilder  ;
	
	private ShowCustomDialog2 showDialog2;
	
	/**投入的倍数临时*/
	private int inputMutipleTmp = 1 ;
	
	private List<Map<String, Object>> list_issue  ;
	
	private boolean flagIsF = true ;
	
	 @Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.buy_intelligence_chase);
		initView();
		getIssue();
		//initFirstData();
		handlerTime.postDelayed(runnable, 1000);
	}

	 //初始化View
	private void initView() {
		btnBack = (Button) findViewById(R.id.top_title_back);
		btnBack.setOnClickListener(this);
		txtTitle = (TextView) findViewById(R.id.top_title_info);
		txtTitle.setText("智能追号");
		btnHelp = (Button) findViewById(R.id.top_title_refres);
		btnHelp.setBackgroundDrawable(null);
		btnHelp.setText("帮助");
		btnHelp.setTextSize(18);
		btnHelp.setTextColor(getResources().getColor(R.color.white));
		btnHelp.setOnClickListener(this);
		
		txtDistanceIssue = (TextView) findViewById(R.id.txt_intell_distance_issue);
		issueName = getIntent().getStringExtra("issueName");
		
		
		txtDistanceIssue.setText("距"+issueName+"期");
		txtStopTime = (TextView) findViewById(R.id.txt_intell_stop_time);
		
		txtTotalIssue = (TextView) findViewById(R.id.txt_intell_total_issue);
		txtIntellRate = (TextView) findViewById(R.id.txt_intell_rate);
		btnUpdate = (Button) findViewById(R.id.btn_intell_update);
		btnUpdate.setOnClickListener(this);
		
		intellChaseListView = (ListView) findViewById(R.id.intelligence_chase_list);
		
		txtChaseTotalIssue = (TextView) findViewById(R.id.txt_intel_chase_tatal_issue);
		txtTatalMoney  =   (TextView) findViewById(R.id.txt_intel_tatal_money);
	
		btnIntellPay = (Button) findViewById(R.id.btn_intell_pay);
		btnIntellPay.setOnClickListener(this);
		
		issueID = getIntent().getStringExtra("issueID");
		lorID = getIntent().getIntExtra("lotID", 0);
		prizeIntellChase =  getIntent().getIntExtra("prizeIntellChase", 0);
		iChaseAdapter =  new IntelligenceChaseAdapter(this);
	
	     alertbBuilder = new ShowCustomDialog2.Builder(context);
	     
	     showDialog2 =  alertbBuilder.createCustomDialog();
	     
		//在listview 追加  一行
		/*TextView txtView = new TextView(this);
		txtView.setText("如需增减期数,请点页面上方的修改按钮");
		txtView.setTextColor(getResources().getColor(R.color.blue_ssqfont));
		txtView.setTextSize(18);
		txtView.setPadding(5, 5, 0, 0);
		intellChaseListView.addFooterView(txtView);*/
	}
	
	
	/**************************************获取期次*Start*****************************/
	private void getIssue(){
		AsyncLoader taskIssure = new AsyncLoader();
		String[] dyn = new String[2];
		JSONObject params = new JSONObject();
		try {
			params.put("LottID", lorID);
			params.put("ChaseCount", castIsuse);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		dyn[0] = params.toString();
		dyn[1] = "2081";
		taskIssure.execute(dyn);
	}
	
	class AsyncLoader extends AsyncTask<String, Integer, String> {
		@Override
		protected String doInBackground(String... params) {
			String strResult = null;
			String action = params[1];
			// 获取请求返回值
			String UserID = ApplicationData.getInstance().getUserID();
			strResult = GetRequestParams.getRequestUserIDResult(params[0], UserID, action, context);
			// 获取请求返回值
			return strResult;
		}
		
		@Override
		protected void onPostExecute(String result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			if (result!=null) {
			 list_issue = new ArrayList<Map<String, Object>>();
				try {
					JSONArray js = new JSONArray(result);
					for(int i =0;i<js.length();i++){
						Map<String, Object> map = new HashMap<String, Object>() ;
						JSONObject json = new JSONObject(js.getString(i));
						map.put("IssueID", json.getString("ID"));
						map.put("IssueName", json.getString("Name"));
						list_issue.add(map) ;
					}
					if (flagIsF) {
						initFirstData();//第一次
					}else {
						initChangeData();//其他
					}
					Log.d("van", "dataList-----" + dataList.toString());
				} catch (Exception e) {
					e.printStackTrace();
				}
			}else {
			}
		}
	}
	/**************************************获取期次*End*****************************/
	
	//第一次初始化数据
	private void initFirstData(){
	    chaseUtil = new IntelligenceChaseUtil(context,issueName,inputMutiple,castIsuse, lorID, prizeIntellChase, model, expectIncome, expectIncomeRate);
	    chaseUtil.setData(list_issue);
	    try {
			dataList = new ArrayList<Map<String, Object>>();
			dataList.addAll(chaseUtil.getDataList()) ;
			int len = dataList.size();
			//Log.d("van", chaseUtil.getDataList().toString());
			txtTatalMoney.setText( Html.fromHtml(String.format("<font color=red>%s</font>元",dataList.get(len-1).get("totalCost").toString())));
			intellChaseListView.setAdapter(iChaseAdapter);
			initTxt();
			showToast("成功生成默认方案");
		} catch (Exception e) {
			//e.printStackTrace();
			showToast("您的设置只适合倍投0期,请重新设置!" );
		}
	}
	
	//第一次 加载   修改方案   文本的显示
	private void initTxt(){
		txtTotalIssue.setText("共"+castIsuse+"期");
		if (model == 1) {
			txtIntellRate.setText("全程最低盈利率"+expectIncomeRate+"%");
		}else {
			txtIntellRate.setText("全程最低盈利"+expectIncome+"元");
		}
		txtChaseTotalIssue.setText("共追"+castIsuse+"期");
	}
	
/************************************************倒计时 刷新***************************************************************/	
	// 倒计时
	Runnable runnable = new Runnable() {
		@Override
		public void run() {
			getCountDown(endTime--);
			handlerTime.postDelayed(this, 1000);
		}
	};
	
	private void getCountDown(long end) {
		if (end > 0) {
			String res = "";
			long temp = 0;
			long d = end / 86400;
			temp = end - (d * 86400);
			if (d>0) {
				res += d + "天";
			}

			long h = temp / 3600;
			if (h>0) {
				res += h + "时";
			}
			temp = temp - (h * 3600);

			long m = temp / 60;
			if (m>0) {
				res += m + "分";
			}
			temp = temp - (m * 60);

			long s = temp;
			res += s + "秒";
			txtStopTime.setText("投注截止:"+res);
		} else {
			txtStopTime.setText("----------");
			asyLoadIssue();
		}
	}
	
	private void asyLoadIssue(){
		GetIDAsyncLoader task = new GetIDAsyncLoader(IntelligenceChaseActivity.this,handlerData,lorID);
		String[] parms = new String[2];
		parms[0] = "200";
		JSONObject jsob = new JSONObject();
		try {
			// 设置请求所需参数
			jsob.put("LottID", lorID);
		} catch (JSONException ex) {
			// TODO Auto-generated catch block
			Log.e("error", ex.toString());
		}
		parms[1] = jsob.toString();
		task.execute(parms);	
	}
	
	//拿到返回的数据
	@SuppressLint("HandlerLeak")
	private Handler handlerData = new Handler() {
		public void handleMessage(android.os.Message msg) {
			try {
				Bundle b = msg.getData();
				issueID = b.getString("issueID");
				if (!(b.getString("issueName")).equals("")) {
					if (!issueName.equals(b.getString("issueName"))) {
						issueName = b.getString("issueName");
						flagIsF = false ;
						getIssue();
						//initChangeData();
						initTxt();
						changeIssue(issueName);
					}
					issueName = b.getString("issueName");
					endTime = b.getLong("endTime");
					Log.d("van", "handler=="+issueID +"--"+issueName +" --"+endTime);
					txtDistanceIssue.setText("距"+issueName+"期");
				}else {
					showToast("未获取到期次");
				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}
	};
	
	//期次改变对话框\
	private void changeIssue(String  issueName){
	    String isssueMsg = "起始期已自动更新为"+issueName+"期"+",请核对期号" ;
	    if (showDialog2 != null) {
	    	showDialog2.cancel();
	    	showDialog2 = null;
	    	alertbBuilder.setTitle("温馨提示");
			alertbBuilder.setMessage(isssueMsg);
			alertbBuilder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					 dialog.dismiss();;
				}
			}) ;
			showDialog2 = alertbBuilder.createCustomDialog();
			showDialog2.show();
		} 
	}
	/************************************************倒计时 刷新* end**************************************************************/		
	
	
	//加1 减2 的  3输入的
		public  void notifyData(int mul, int postion , int isFormAddOrSub){
			//Log.d("van", "---"+mul+"-------"+postion);
			inputMutiple =  mul++; //改变的倍数
			int temp1TotalCost = 0;
			 
		    previousTotalCost =  Integer.parseInt( dataList.get(postion).get("totalCost").toString());;
			 
			if (isFormAddOrSub == 1) {
				 temp1TotalCost  =   tempCastCount*2 +  previousTotalCost;
			}else if (isFormAddOrSub == 2) {
				 temp1TotalCost  =  previousTotalCost -  tempCastCount*2  ;
			} 
			double temp1TotalIncome =  inputMutiple * prizeIntellChase - temp1TotalCost ;
			dataList.get(postion).put("castMutiple", inputMutiple);
			dataList.get(postion).put("totalCost", temp1TotalCost);
			dataList.get(postion).put("totalIncome", temp1TotalIncome);
			dataList.get(postion).put("incomeRate", temp1TotalIncome / temp1TotalCost * 100);
			for (int i = 0; i < dataList.size(); i++) {
				if (i > postion) {
					tmepTotalCost = Integer.parseInt( dataList.get(i).get("totalCost").toString());
					double tempprizeIntellChase = Integer.parseInt( dataList.get(i).get("castMutiple").toString())*prizeIntellChase;
					int temp2TotalCost = 0 ;
					if (isFormAddOrSub == 1) {
						temp2TotalCost  = tmepTotalCost + 2 * tempCastCount;
					}else if (isFormAddOrSub == 2) {
						temp2TotalCost  = tmepTotalCost - 2 * tempCastCount;
					}/* if (isFormAddOrSub == 3 ) {
						temp2TotalCost  = tmepTotalCost + castCount*2   ;
					}*/
					double temp2TotalIncome =   tempprizeIntellChase - temp2TotalCost ;
					dataList.get(i).put("totalCost", temp2TotalCost);
					dataList.get(i).put("totalIncome", temp2TotalIncome);
					dataList.get(i).put("incomeRate", temp2TotalIncome / temp2TotalCost * 100);
				}
				
			}
			iChaseAdapter.notifyDataSetChanged();
			int len = dataList.size() ;
			//getMinData(dataList);
			txtTatalMoney.setText( Html.fromHtml(String.format("<font color=red>%s</font>元",dataList.get(len-1).get("totalCost").toString())));
			changTxt();
		}
	
	//改变的文本  +  -
	private void changTxt (){
		txtTotalIssue.setText("共"+castIsuse+"期");
		txtChaseTotalIssue.setText("共追"+castIsuse+"期");
		int len = dataList.size();
		if (len != 0) {
			int [] valus = new int[len] ;
			if (model == 1) {
				for (int i = 0; i < len  ; i++) {
					int  data  = (int) Double.parseDouble((dataList.get(i).get("incomeRate").toString()));
					valus[i] = data;
				}
				Arrays.sort(valus);
				txtIntellRate.setText("全程最低盈利率"+valus[0]+"%");
			}else {
				for (int i = 0; i < len  ; i++) {
					int  data  = (int) Double.parseDouble((dataList.get(i).get("totalIncome").toString()));
					valus[i] = data;
				}
				Arrays.sort(valus);
				txtIntellRate.setText("全程最低盈利"+valus[0]+"元");
			}
		}else {
			
		}
	}
	
	
	

	
	//期次变化   改变方案   数据
	private void initChangeData(){
		try {
			dataList.clear();
			chaseUtil = new IntelligenceChaseUtil(context ,issueName,inputMutiple,castIsuse, lorID, prizeIntellChase, model, expectIncome, expectIncomeRate);
			chaseUtil.setData(list_issue);
			dataListNew = chaseUtil.getDataList() ;
			dataList.addAll(dataListNew);
			//Log.d("van", dataList.toString());
			int len = dataList.size() ;
			//getMinData(dataList);
			txtTatalMoney.setText( Html.fromHtml(String.format("<font color=red>%s</font>元",dataList.get(len-1).get("totalCost").toString())));
			iChaseAdapter.notifyDataSetChanged();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			//e.printStackTrace();
			//恢复默认
			inputMutiple = 1 ;
			castIsuse = 10 ;
		    expectIncome = 100;
		    expectIncomeRate = 30 ;
			flagIsF = true ;
			getIssue();
		}
	}
 
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if (20000 == resultCode) {
			castIsuse = Integer.parseInt( data.getStringExtra("inputIssue")) ;
			inputMutipleTmp  =  Integer.parseInt( data.getStringExtra("inputMul"));
			//tempCastCount = inputMutipleTmp ;
			inputMutiple = inputMutipleTmp ;
			expectIncomeRate =  Integer.parseInt(data.getStringExtra("inputIncomeRate"));
			expectIncome = Integer.parseInt(  data.getStringExtra("inputIncome"));
			intWinStopChase =  data.getIntExtra("intWinStopChase", 1);
			model =  data.getIntExtra("model", 1);
			flagIsF = false ;
			getIssue();
			//initChangeData();
			initTxt();
		}
	}
	
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			Intent data=new Intent(); 
			data.putExtra("issueName", issueName);
			setResult(Constants.ZNZH_RES_CODE, data);
			IntelligenceChaseActivity.this.finish();
			return true;
		}else {
			return super.onKeyDown(keyCode, event);
		}
	}

	@Override
	public void onClick(View v) {
		
		switch (v.getId()) {
		case R.id.top_title_back:
			Intent data=new Intent(); 
			data.putExtra("issueName", issueName);
			setResult(Constants.ZNZH_RES_CODE, data);
			IntelligenceChaseActivity.this.finish();
			break;
		case R.id.top_title_refres:
			//showToast("玩法介绍");
			Intent intentHelp = new Intent(IntelligenceChaseActivity.this, CaiPiaoHelp.class);
			intentHelp.putExtra("cp_url", "znzh.html");
			intentHelp.putExtra("cp_title", "智能追号");
			startActivity(intentHelp);
			break;
			
		case R.id.btn_intell_update:
			Intent intent = new Intent(IntelligenceChaseActivity.this, IntelligenceChaseUpdatePlan.class);
			intent.putExtra("lorID", lorID);
			intent.putExtra("issueName", issueName);
			intent.putExtra("castIsuse", castIsuse);
			intent.putExtra("inputMutiple", inputMutipleTmp);
			intent.putExtra("expectIncomeRate", expectIncomeRate);
			intent.putExtra("expectIncome", expectIncome);
			intent.putExtra("model", model);
			intent.putExtra("intWinStopChase", intWinStopChase);
			startActivityForResult(intent, 1001);
			break;
			
		case R.id.btn_intell_pay:
			if (AppUtils.checkUserLogin()) {
				if (dataList.size() != 0) {
					startZhuiHaoThread();
				}else {
                     showToast("请重新设置追号!");					
				}
			}else {
				Intent intentL = new Intent();
				intentL.setClass(context, LoginActivity.class);
				startActivity(intentL);
			}
			break;

		default:
			break;
		}
		
	}
	
	
	
	/*************购买*****************/
	private void startZhuiHaoThread() {
		int len = dataList.size() ;
		buyMoney = Integer.parseInt( dataList.get(len-1).get("totalCost").toString() );
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		list.addAll( Constants.LIST_LOTNUM) ;
		Log.d("van", list.toString());
		AsyncZNZHLoader loader = new AsyncZNZHLoader() ;
		dyn = new String[2];
		JSONObject params = new JSONObject();
		try {
			JSONArray array = new JSONArray();
			JSONArray arrayLOTNUM = new JSONArray();
			for (int i = 0; i < list.size(); i++) {
				JSONObject o = new JSONObject(list.get(i));
				arrayLOTNUM.put(o);
			}
			for (int k = 0; k < len ; k++) {
				int bs = Integer.parseInt( dataList.get(k).get("castMutiple").toString());
				JSONObject json = new JSONObject();
				json.put("IssueID", dataList.get(k).get("IssueID").toString());
				json.put("LotteryNumber", arrayLOTNUM);
				json.put("Multiple", bs);
				json.put("Money", bs * 2);
				array.put(json);
			}
			params.put("StopMoney", intWinStopChase);
			params.put("SumNum", 1);//单期号码注数（未乘倍数）
			params.put("BuyMoney", buyMoney);//认购金额
			params.put("ChaseIsuses", array);
			params.put("LottID", lorID);
		} catch (JSONException ex) {
			Log.e("error", ex.toString());
		}
		dyn[0] = params.toString();
		dyn[1] = "208";
		loader.execute(dyn);
		
	}
	
	
	class AsyncZNZHLoader extends AsyncTask<String, Integer, String> {
		String action;
		ShowTipDialog showdialog = new ShowTipDialog();
		// 1.准备运行
		protected void onPreExecute() {
			showdialog.showDialog(IntelligenceChaseActivity.this);
		}
		@Override
		protected String doInBackground(String... params) {
			// 处理后台执行的任务，在后台线程执行
			String strResult = null;
			action = params[1];
			// 获取请求返回值
			String UserID = ApplicationData.getInstance().getUserID();
			strResult = GetRequestParams.getRequestUserIDResult(params[0], UserID, action, getApplicationContext());
			// 获取请求返回值
			return strResult;
		} 
		// .完成后台任务
		protected void onPostExecute(String result) {
			if (result != null) {
					ZNZHBuy(result);
					Log.d("van", "--zn--"+result);
				showdialog.closeDialog();
			} else {
				Toast.makeText(IntelligenceChaseActivity.this, getString(R.string.problem_01), Toast.LENGTH_LONG).show();
			}
		}

	
	}
	//智能追号 结果
	private void ZNZHBuy(String strResult) {
		try {
			JSONTokener jsonParser = new JSONTokener(strResult);
			JSONObject js = (JSONObject) jsonParser.nextValue();
			
			if (Integer.parseInt(js.getString("Code")) < 0) {
				String balanceNotFull = js.getString("Data");
				Log.d("van", balanceNotFull+"-------");
				showDialog(balanceNotFull);
			} else {
				buy_icon = R.drawable.buy_success;
				String msg = "";
				msg = "成功连续追号" + castIsuse + "期\n" + "\n我的认购：" + buyMoney
						+ "元\n账户余额：" + js.getString("Msg").toString() + "元";
		       new ShowTipDialog().showBuyInfoZH(IntelligenceChaseActivity.this, msg, "追号记录", buy_icon, dyn[0]);
			}
		} catch (Exception ex) {
			// 异常处理代码
			Log.e("error", ex.toString());
		}
	}
	
	//弹出对话框
	private void showDialog(String balanceNotFull){
		// 跳转至-开奖信息主页面
		String msg = balanceNotFull;
		ShowCustomDialog.Builder alertbBuilder = new ShowCustomDialog.Builder(context);
	    alertbBuilder.setTitle("购买失败");
	    if (msg.contains(Constants.BALANCE_BUZU)) {
	    alertbBuilder.setMessage("您的余额不足，请充值在购买");
	    alertbBuilder.setNegativeButton("充值", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				Intent intent = new Intent();
				 intent.setClass(context, JddRechargeListActivity.class);
				 startActivity(intent);;
				 dialog.dismiss();
			}
		}).setPositiveButton("取消", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				 
				 dialog.dismiss();
			}
		}) 
		.createCustomDialog().show();
	    }
	    //追号失败
	    else if (msg.contains(Constants.ZNZH_FAIUL)) {
			alertbBuilder.setMessage(msg);
			alertbBuilder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					 dialog.cancel();
			
				}
			}) 
			.createCustomDialog().show();
		}
	    //期次销售
	    else if (msg.contains(Constants.BALANCE_CUT)) {
			alertbBuilder.setMessage(msg);
			alertbBuilder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					 dialog.cancel();
			
				}
			}) 
			.createCustomDialog().show();
		}//系统忙
		else if (msg.contains(Constants.BALANCE_SYSTEM_EXC)) {
			alertbBuilder.setMessage(msg);
			alertbBuilder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					 dialog.cancel();
			
				}
			}) 
			.createCustomDialog().show();
		}
		//该期投注 
		else if (msg.contains(Constants.BALANCE_CURRISS_STOP)) {
			alertbBuilder.setMessage(msg);
			alertbBuilder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					 dialog.cancel();
			
				}
			}) 
			.createCustomDialog().show();
		}
	    else {
			alertbBuilder.setMessage(msg);
			alertbBuilder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					 dialog.cancel();
			
				}
			}) 
			.createCustomDialog().show();
		}
	}
	
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
	handlerTime.removeCallbacks(runnable);
	asyLoadIssue();
	handlerTime.postDelayed(runnable, 1000);
	}
	
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
	handlerTime.removeCallbacks(runnable);
	
	}
	
	/**内部类 BaseAdapter */
	public class IntelligenceChaseAdapter extends BaseAdapter {

		/** 上下文 */
		private Context context;
		/** LayoutInflater */
		private LayoutInflater inflater = null;
		
		/**最大 倍数*/
		private int issueMaxMul = 99999 ;
		
		public IntelligenceChaseAdapter(Context context) {
			super();
			inflater = LayoutInflater.from(context);
		}
		
		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return dataList.size();
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return dataList.get(position);
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		@Override
		public View getView(final int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			if (convertView == null) {
				convertView=	inflater.inflate(R.layout.buy_intelligence_chase_list_item, null);
			}
			//序号
			TextView txt_intell_No = (TextView) convertView.findViewById(R.id.txt_intell_No);
			int Num = position + 1 ; 
			txt_intell_No.setText(Integer.toString(Num));
			
			//期次
			TextView txt_intell_issue = (TextView) convertView.findViewById(R.id.txt_intell_issue);
		    if (dataList.get(position).get("issueName").toString() != null) {
		    	txt_intell_issue.setText(dataList.get(position).get("issueName").toString());
			}
			
			
			//倍数
			final EditText edt_intell_input_mul = (EditText) convertView.findViewById(R.id.edt_intell_input_mul);
			edt_intell_input_mul.setText(Integer.parseInt(dataList.get(position).get("castMutiple").toString()) + "" );
			
			/*edt_intell_input_mul.setOnFocusChangeListener(new OnFocusChangeListener() {
				
				@Override
				public void onFocusChange(View v, boolean hasFocus) {
					// TODO Auto-generated method stub
					if (hasFocus) {
						edt_intell_input_mul.selectAll();
					}
				}
			});
			//监听 文本框 输入
			edt_intell_input_mul.addTextChangedListener(new TextWatcher() {
				private boolean isChanged = false;
				int inputMul = 1;//输入的倍数
				@Override
				public void afterTextChanged(Editable s) {
					if(isChanged){
			            return ;
			        }
					
					Log.d("van", "afterTextChanged:" + s.toString());
					
					isChanged = true;
					if (!AppUtils.isBlank(s.toString())) {
						if (s.toString().equals("")) {
							edt_intell_input_mul.setText(Integer.toString(1));
						}else {
							inputMul = Integer.parseInt(s.toString());
						}
						if (Integer.parseInt(s.toString())<1) {
							 showToast(R.string.input_least_mul);
							 edt_intell_input_mul.setText(Integer.toString(1));
							// notifyData(Integer.parseInt(edt_intell_input_mul.getText().toString().toString()),position ,dataList.get(position).get("issueName").toString(),3);//3 是输入
						}else if(Integer.parseInt(s.toString())>issueMaxMul){
							showToast("超过最大倍数");
							edt_intell_input_mul.setText(""+issueMaxMul);
							//notifyData(Integer.parseInt(edt_intell_input_mul.getText().toString().toString()),position ,dataList.get(position).get("issueName").toString(),3);//3 是输入
						}
							//edt_intell_input_mul.setText(Integer.toString(inputMul));
//						edt_intell_input_mul.setSelection(edt_intell_input_mul.length());
//						 edt_intell_input_mul.invalidate();
					}else {
						edt_intell_input_mul.setText(Integer.toString(1));
						//notifyData(Integer.parseInt(edt_intell_input_mul.getText().toString().toString()),position ,dataList.get(position).get("issueName").toString(),3);//3 是输入
					}
					notifyData(Integer.parseInt(edt_intell_input_mul.getText().toString()),position ,3);//3 是输入
					isChanged = false;
				}
				@Override
				public void onTextChanged(CharSequence s, int start, int before, int count) {
				}
				
				@Override
				public void beforeTextChanged(CharSequence s, int start, int count, int after) {
				}
			});*/
			
			
			//减
			Button btnSub = (Button) convertView.findViewById(R.id.btn_intell_sub);
			btnSub.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					int intInputMul = Integer.parseInt(edt_intell_input_mul.getText().toString().trim())	 ;
					if (intInputMul < 1) {
						edt_intell_input_mul.setText("1");
					}else {
						intInputMul -- ;
						if (intInputMul == 0) {
							edt_intell_input_mul.setText("1");
						}else {
//							edt_intell_input_mul.setText(intInputMul+"");	
							notifyData(intInputMul,position ,2);//2 是减
						}
					}
					
					
				}
			});
			
			
			//加
			Button btnAdd = (Button) convertView.findViewById(R.id.btn_intell_add);
			btnAdd.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					int intInputMul = Integer.parseInt(edt_intell_input_mul.getText().toString().trim())	 ;
					if (intInputMul > issueMaxMul) {
						edt_intell_input_mul.setText(issueMaxMul+"");
					}else {
						intInputMul ++ ;
						if (intInputMul == issueMaxMul) {
							edt_intell_input_mul.setText(issueMaxMul+"");
						}else {
//							edt_intell_input_mul.setText(intInputMul+"");	
							//Log.d("van", intInputMul+",,,,," + position);
//							dataList.get(position).put("currentCost", intInputMul);
					        notifyData(intInputMul,position,1);//1 是加
						}
					}
					
					
				}
			});
			
			
			//累计投入
			TextView txt_intell_addup_input = (TextView) convertView.findViewById(R.id.txt_intell_addup_input);
			txt_intell_addup_input.setText(dataList.get(position).get("totalCost").toString());
			
			//中奖盈利
			TextView txt_intell_win_profit = (TextView) convertView.findViewById(R.id.txt_intell_win_profit);
			txt_intell_win_profit.setText(	(int) Double.parseDouble((dataList.get(position).get("totalIncome").toString())) +"");
			
			//盈利率
			TextView txt_intell_profit_rate = (TextView) convertView.findViewById(R.id.txt_intell_profit_rate);
			txt_intell_profit_rate.setText((int) Double.parseDouble((dataList.get(position).get("incomeRate").toString()))+"%");
			
			return convertView ;
		}

	}
	

}
